/**
 * AI命令面板组件
 * 提供快捷命令和智能操作
 */

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Modal, Input, List, Tag, Space, Avatar, Empty, Spin } from 'antd';
import {
  SearchOutlined,
  ThunderboltOutlined,
  EditOutlined,
  FileTextOutlined,
  BulbOutlined,
  FormatPainterOutlined,
  TranslationOutlined,
  BarChartOutlined,
  PictureOutlined,
  LinkOutlined,
  CheckCircleOutlined,
  RocketOutlined,
} from '@ant-design/icons';
import { aiCopilotService } from '@/services/ai-copilot.service';
import './style.css';

interface CommandItem {
  id: string;
  title: string;
  description: string;
  category: 'generate' | 'edit' | 'format' | 'insert' | 'analyze';
  icon: React.ReactNode;
  shortcut?: string;
  action: (context: CommandContext) => void | Promise<void>;
}

interface CommandContext {
  selectedText: string;
  cursorPosition: number;
  fullText: string;
  onInsert: (text: string) => void;
  onReplace: (text: string) => void;
}

interface CommandPaletteProps {
  visible: boolean;
  onClose: () => void;
  context: CommandContext;
}

export const CommandPalette: React.FC<CommandPaletteProps> = ({
  visible,
  onClose,
  context,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredCommands, setFilteredCommands] = useState<CommandItem[]>([]);
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [executing, setExecuting] = useState(false);

  const inputRef = useRef<any>(null);

  // 定义所有可用命令
  const commands: CommandItem[] = [
    {
      id: 'continue-writing',
      title: '继续写作',
      description: '让AI继续当前段落的写作',
      category: 'generate',
      icon: <EditOutlined />,
      shortcut: 'Tab Tab',
      action: async (ctx) => {
        const continuation = await generateContinuation(ctx.fullText, ctx.cursorPosition);
        ctx.onInsert(continuation);
      },
    },
    {
      id: 'expand-selection',
      title: '扩展内容',
      description: '展开选中的文本，添加更多细节',
      category: 'edit',
      icon: <RocketOutlined />,
      shortcut: 'Ctrl+E',
      action: async (ctx) => {
        if (ctx.selectedText) {
          const expanded = await expandText(ctx.selectedText);
          ctx.onReplace(expanded);
        }
      },
    },
    {
      id: 'simplify-text',
      title: '简化表达',
      description: '让文字更简洁易懂',
      category: 'edit',
      icon: <FormatPainterOutlined />,
      action: async (ctx) => {
        if (ctx.selectedText) {
          const simplified = await simplifyText(ctx.selectedText);
          ctx.onReplace(simplified);
        }
      },
    },
    {
      id: 'add-example',
      title: '添加例子',
      description: '为观点添加具体的例子',
      category: 'insert',
      icon: <FileTextOutlined />,
      action: async (ctx) => {
        const example = await generateExample(ctx.selectedText || ctx.fullText);
        ctx.onInsert(`\n\n例如：${example}`);
      },
    },
    {
      id: 'add-data',
      title: '添加数据',
      description: '插入相关的统计数据',
      category: 'insert',
      icon: <BarChartOutlined />,
      action: async (ctx) => {
        const data = await generateDataPoint(ctx.selectedText || ctx.fullText);
        ctx.onInsert(`\n\n根据数据显示：${data}`);
      },
    },
    {
      id: 'add-quote',
      title: '添加引用',
      description: '插入相关的名言或引用',
      category: 'insert',
      icon: <LinkOutlined />,
      action: async (ctx) => {
        const quote = await generateQuote(ctx.selectedText || ctx.fullText);
        ctx.onInsert(`\n\n> ${quote}`);
      },
    },
    {
      id: 'translate',
      title: '翻译',
      description: '翻译选中的文本',
      category: 'edit',
      icon: <TranslationOutlined />,
      action: async (ctx) => {
        if (ctx.selectedText) {
          const translated = await translateText(ctx.selectedText);
          ctx.onReplace(translated);
        }
      },
    },
    {
      id: 'improve-clarity',
      title: '提高清晰度',
      description: '让表达更清晰明了',
      category: 'edit',
      icon: <BulbOutlined />,
      action: async (ctx) => {
        if (ctx.selectedText) {
          const improved = await improveClarityText(ctx.selectedText);
          ctx.onReplace(improved);
        }
      },
    },
    {
      id: 'add-transition',
      title: '添加过渡',
      description: '添加过渡句，使文章更连贯',
      category: 'insert',
      icon: <ThunderboltOutlined />,
      action: async (ctx) => {
        const transition = await generateTransition(ctx.fullText, ctx.cursorPosition);
        ctx.onInsert(`\n\n${transition}\n\n`);
      },
    },
    {
      id: 'suggest-image',
      title: '建议配图',
      description: '为当前内容推荐配图描述',
      category: 'insert',
      icon: <PictureOutlined />,
      action: async (ctx) => {
        const imageDesc = await suggestImage(ctx.selectedText || ctx.fullText);
        ctx.onInsert(`\n\n[图片：${imageDesc}]`);
      },
    },
    {
      id: 'fix-grammar',
      title: '修复语法',
      description: '检查并修复语法错误',
      category: 'edit',
      icon: <CheckCircleOutlined />,
      action: async (ctx) => {
        if (ctx.selectedText) {
          const fixed = await fixGrammar(ctx.selectedText);
          ctx.onReplace(fixed);
        }
      },
    },
  ];

  // 过滤命令
  useEffect(() => {
    if (!searchQuery) {
      setFilteredCommands(commands);
    } else {
      const query = searchQuery.toLowerCase();
      const filtered = commands.filter(
        (cmd) =>
          cmd.title.toLowerCase().includes(query) ||
          cmd.description.toLowerCase().includes(query) ||
          cmd.category.toLowerCase().includes(query)
      );
      setFilteredCommands(filtered);
    }
    setSelectedIndex(0);
  }, [searchQuery]);

  // 键盘导航
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!visible) return;

      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setSelectedIndex((prev) =>
          prev < filteredCommands.length - 1 ? prev + 1 : prev
        );
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
      } else if (e.key === 'Enter') {
        e.preventDefault();
        executeCommand(filteredCommands[selectedIndex]);
      } else if (e.key === 'Escape') {
        onClose();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [visible, selectedIndex, filteredCommands]);

  // 自动聚焦输入框
  useEffect(() => {
    if (visible) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
    }
  }, [visible]);

  // 执行命令
  const executeCommand = async (command: CommandItem) => {
    if (!command || executing) return;

    setExecuting(true);
    try {
      await command.action(context);
      onClose();
    } catch (error) {
      console.error('Failed to execute command:', error);
    } finally {
      setExecuting(false);
    }
  };

  // 获取分类颜色
  const getCategoryColor = (category: string) => {
    const colors: Record<string, string> = {
      generate: 'blue',
      edit: 'green',
      format: 'orange',
      insert: 'purple',
      analyze: 'red',
    };
    return colors[category] || 'default';
  };

  return (
    <Modal
      title="AI 命令面板"
      visible={visible}
      onCancel={onClose}
      footer={null}
      width={600}
      className="command-palette-modal"
      bodyStyle={{ padding: 0 }}
    >
      {/* 搜索框 */}
      <div className="command-search">
        <Input
          ref={inputRef}
          prefix={<SearchOutlined />}
          placeholder="输入命令或描述..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          size="large"
          bordered={false}
        />
      </div>

      {/* 命令列表 */}
      <div className="command-list">
        {executing ? (
          <div className="command-executing">
            <Spin tip="正在执行..." />
          </div>
        ) : filteredCommands.length > 0 ? (
          <List
            dataSource={filteredCommands}
            renderItem={(item, index) => (
              <List.Item
                className={`command-item ${index === selectedIndex ? 'selected' : ''}`}
                onClick={() => executeCommand(item)}
                onMouseEnter={() => setSelectedIndex(index)}
              >
                <List.Item.Meta
                  avatar={
                    <Avatar
                      icon={item.icon}
                      style={{
                        backgroundColor: 'transparent',
                        color: '#667eea',
                      }}
                    />
                  }
                  title={
                    <Space>
                      <span>{item.title}</span>
                      <Tag color={getCategoryColor(item.category)} style={{ fontSize: '11px' }}>
                        {item.category}
                      </Tag>
                      {item.shortcut && (
                        <span className="command-shortcut">{item.shortcut}</span>
                      )}
                    </Space>
                  }
                  description={item.description}
                />
              </List.Item>
            )}
          />
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="没有找到匹配的命令"
            style={{ padding: '40px' }}
          />
        )}
      </div>

      {/* 提示信息 */}
      <div className="command-footer">
        <Space size="large">
          <span>
            <kbd>↑↓</kbd> 导航
          </span>
          <span>
            <kbd>Enter</kbd> 执行
          </span>
          <span>
            <kbd>Esc</kbd> 关闭
          </span>
        </Space>
      </div>
    </Modal>
  );
};

// 辅助函数：生成续写
async function generateContinuation(text: string, position: number): Promise<string> {
  // TODO: 调用实际的AI服务
  return '这是AI生成的续写内容...';
}

// 辅助函数：扩展文本
async function expandText(text: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return `${text}\n\n[扩展内容：这里添加更多细节和解释...]`;
}

// 辅助函数：简化文本
async function simplifyText(text: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return text.split('.')[0] + '.';
}

// 辅助函数：生成例子
async function generateExample(context: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return '这是一个具体的例子...';
}

// 辅助函数：生成数据点
async function generateDataPoint(context: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return '根据最新统计，有80%的用户认为...';
}

// 辅助函数：生成引用
async function generateQuote(context: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return '"创新是进步的灵魂。" —— 某位名人';
}

// 辅助函数：翻译文本
async function translateText(text: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return `[Translation: ${text}]`;
}

// 辅助函数：提高清晰度
async function improveClarityText(text: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return text;
}

// 辅助函数：生成过渡句
async function generateTransition(text: string, position: number): Promise<string> {
  // TODO: 调用实际的AI服务
  return '基于以上分析，我们可以进一步探讨...';
}

// 辅助函数：建议配图
async function suggestImage(context: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return '展示数据趋势的折线图';
}

// 辅助函数：修复语法
async function fixGrammar(text: string): Promise<string> {
  // TODO: 调用实际的AI服务
  return text;
}